package cn.iocoder.yudao.module.member.service.userwithdraw;

import cn.iocoder.yudao.module.infra.util.file.FileUploadUtils;
import cn.iocoder.yudao.module.infra.util.file.vo.FileUploadVo;
import cn.iocoder.yudao.module.member.controller.app.userwithdraw.vo.AppUserWithdrawSaveReqVO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.member.enums.userwithdraw.WithdrawStatusEnum;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.member.service.usercommission.UserCommissionService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;

import cn.iocoder.yudao.module.member.controller.admin.userwithdraw.vo.*;
import cn.iocoder.yudao.module.member.dal.dataobject.userwithdraw.UserWithdrawDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.member.dal.mysql.userwithdraw.UserWithdrawMapper;
import org.springframework.web.multipart.MultipartFile;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;

/**
 * 提现 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class UserWithdrawServiceImpl implements UserWithdrawService {

    @Value("${zhima.withdraw-options}")
    private List<Integer> withdrawOptions;

    @Resource
    private UserWithdrawMapper userWithdrawMapper;
    @Resource
    private MemberUserService memberUserService;
    @Resource
    private UserCommissionService userCommissionService;
    @Resource
    private FileUploadUtils fileUploadUtils;

    @Override
    public Long createUserWithdraw(UserWithdrawSaveReqVO createReqVO) {
        // 插入
        UserWithdrawDO userWithdraw = BeanUtils.toBean(createReqVO, UserWithdrawDO.class);
        userWithdrawMapper.insert(userWithdraw);
        // 返回
        return userWithdraw.getId();
    }

    private Boolean inWithDrawOptions(Integer withdraw) {
        for (Integer withdrawOption : withdrawOptions) {
            if (withdrawOption.equals(withdraw)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Long createUserWithdrawForApp(AppUserWithdrawSaveReqVO createReqVOApp) {
        Long userId = createReqVOApp.getUserId();
        if (!inWithDrawOptions(createReqVOApp.getWithdraw())) {
            throw exception(ErrorCodeConstants.USER_WITHDRAW_NOT_RIGHT);
        }
        Integer totalCommission = userCommissionService.totalCommissionByUserId(userId);
        Integer totalWithdraw = totalWithdrawByUserId(userId);
        Integer availableWithdraw = withdrawAvailable(totalCommission - totalWithdraw);
        if (availableWithdraw < createReqVOApp.getWithdraw()) {
            throw exception(ErrorCodeConstants.USER_WITHDRAW_NOT_ENOUGH);
        }
        UserWithdrawSaveReqVO createReqVO = new UserWithdrawSaveReqVO();
        BeanUtils.copyProperties(createReqVOApp, createReqVO);
        return createUserWithdraw(createReqVO);
    }

    @Override
    public Boolean updateUserWithdraw(UserWithdrawUpdateReqVO updateReqVO) {
        // 校验存在
        validateUserWithdrawExists(updateReqVO.getId());
        // 更新
//        UserWithdrawDO updateObj = BeanUtils.toBean(updateReqVO, UserWithdrawDO.class);
//        userWithdrawMapper.updateById(updateObj);
        LambdaUpdateWrapper<UserWithdrawDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(UserWithdrawDO::getStatus, updateReqVO.getStatus())
                .set(StringUtils.isNoneEmpty(updateReqVO.getScreenshotUrl()), UserWithdrawDO::getScreenshotUrl, updateReqVO.getScreenshotUrl())
                .set(StringUtils.isNoneEmpty(updateReqVO.getAliNo()), UserWithdrawDO::getAliNo, updateReqVO.getAliNo())
                .set(StringUtils.isNoneEmpty(updateReqVO.getRemark()), UserWithdrawDO::getRemark, updateReqVO.getRemark())
                .eq(UserWithdrawDO::getId, updateReqVO.getId());
        return userWithdrawMapper.update(lambdaUpdateWrapper) > 0;
    }

    @Override
    public Boolean updateUserWithdraw(Long id, MultipartFile[] files, Integer status, String aliNo, String remark) {
        // 校验存在
        validateUserWithdrawExists(id);
        LambdaUpdateWrapper<UserWithdrawDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        if (Objects.nonNull(files) && (files.length > 0)) {
            FileUploadVo fileUploadVo = fileUploadUtils.upload(files, 1, 10 * 1024 * 1024L);
            lambdaUpdateWrapper.set(UserWithdrawDO::getScreenshotUrl, fileUploadVo.fileUrls.get(0));
        }
        lambdaUpdateWrapper.set(UserWithdrawDO::getStatus, status)
                .set(StringUtils.isNoneEmpty(aliNo), UserWithdrawDO::getAliNo, aliNo)
                .set(StringUtils.isNoneEmpty(remark), UserWithdrawDO::getRemark, remark)
                .eq(UserWithdrawDO::getId, id);
        return userWithdrawMapper.update(lambdaUpdateWrapper) > 0;
    }

    @Override
    public void deleteUserWithdraw(Long id) {
        // 校验存在
        validateUserWithdrawExists(id);
        // 删除
        userWithdrawMapper.deleteById(id);
    }

    private void validateUserWithdrawExists(Long id) {
        if (userWithdrawMapper.selectById(id) == null) {
            throw exception(USER_WITHDRAW_NOT_EXISTS);
        }
    }

    @Override
    public UserWithdrawDO getUserWithdraw(Long id) {
        return userWithdrawMapper.selectById(id);
    }

    @Override
    public PageResult<UserWithdrawRespVO> getUserWithdrawPage(UserWithdrawPageReqVO pageReqVO) {
        if (Objects.nonNull(pageReqVO.getMobile())) {
            MemberUserDO memberUserDO = memberUserService.getUserByMobile(pageReqVO.getMobile());
            if (Objects.nonNull(memberUserDO)) {
                pageReqVO.setUserId(memberUserDO.getId());
            }
        } else if (Objects.nonNull(pageReqVO.getInviteCode())) {
            MemberUserDO memberUserDO = memberUserService.getUserByInviteCode(pageReqVO.getInviteCode());
            if (Objects.nonNull(memberUserDO)) {
                pageReqVO.setUserId(memberUserDO.getId());
            }
        }
        PageResult<UserWithdrawDO> pageResult = userWithdrawMapper.selectPage(pageReqVO);
        PageResult<UserWithdrawRespVO> userWithdrawRespVOPageResult = BeanUtils.toBean(pageResult, UserWithdrawRespVO.class);
        List<UserWithdrawRespVO> userWithdrawRespVOList = userWithdrawRespVOPageResult.getList();
        for (UserWithdrawRespVO userWithdrawRespVO : userWithdrawRespVOList) {
            Long userId = userWithdrawRespVO.getUserId();
            MemberUserDO memberUserDO = memberUserService.getUser(userId);
            if (Objects.nonNull(memberUserDO)) {
                userWithdrawRespVO.setNickname(memberUserDO.getNickname());
            }
            Integer firstInviteRecharge = userCommissionService.firstTotalRecharge(userId);
            userWithdrawRespVO.setRechargeStatus(firstInviteRecharge > 0);
            userWithdrawRespVO.setCumulativeRecharge(firstInviteRecharge);
            userWithdrawRespVO.setInvitedRecharge(userCommissionService.secondTotalRecharge(userId));
            userWithdrawRespVO.setScreenshotUrl(fileUploadUtils.imagePrefixUrl + userWithdrawRespVO.getScreenshotUrl());
        }
        userWithdrawRespVOPageResult.setList(userWithdrawRespVOList);
        return userWithdrawRespVOPageResult;
    }

    @Override
    public Integer totalWithdrawByStatus(Integer status) {
        Integer totalWithdraw = userWithdrawMapper.totalWithdrawByStatus(status);
        return Objects.isNull(totalWithdraw) ? 0 : totalWithdraw;
    }

    @Override
    public Integer totalWithdrawByUserId(Long userId) {
        Integer totalWithdraw = userWithdrawMapper.totalWithdrawByUserId(userId);
        return Objects.isNull(totalWithdraw) ? 0 : totalWithdraw;
    }

    public Integer totalWithdrawByUserIdAndStatus(Long userId, Integer status) {
        Integer totalWithdraw = userWithdrawMapper.totalWithdrawByUserIdAndStatus(userId, status);
        return Objects.isNull(totalWithdraw) ? 0 : totalWithdraw;
    }

    @Override
    public Integer totalWithdrawByUserIdAndStatusSucc(Long userId) {
        return totalWithdrawByUserIdAndStatus(userId, WithdrawStatusEnum.SUCCESS.getCode());
    }

    @Override
    public Integer withdrawAvailable(Integer commission) {
        int length = withdrawOptions.size();
        for (int i = (length - 1); i >= 0; i--) {
            Integer withdrawOption = withdrawOptions.get(i);
            if (commission >= withdrawOption) {
                return withdrawOption;
            }
        }
        return 0;
    }

    @Override
    public UserWithdrawStatisticsRespVO getUserWithdrawStatistics() {
        UserWithdrawStatisticsRespVO userWithdrawStatisticsRespVO = new UserWithdrawStatisticsRespVO();
        userWithdrawStatisticsRespVO.setWithdrawWait(totalWithdrawByStatus(WithdrawStatusEnum.WAITING.getCode()));
        userWithdrawStatisticsRespVO.setWithdrawSucc(totalWithdrawByStatus(WithdrawStatusEnum.SUCCESS.getCode()));
        return userWithdrawStatisticsRespVO;
    }

}